let root = [3, 9, 20, 15, 7]
function TreeNode(val, left, right) {
    this.val = (val === undefined ? 0 : val)
    this.left = (left === undefined ? null : left)
    this.right = (right === undefined ? null : right)
}
function arrayToTree(arr) {
    const root = new TreeNode(arr[0])
    const queue = [root]
    let i = 1
    while (queue.length > 0) {
        const cur = queue.shift()
        if (i < arr.length && arr[i] !== null) {
            const left = new TreeNode(arr[i])
            queue.push(left)
            cur.left = left
        }
        i++
        if (i < arr.length && arr[i] !== null) {
            const right = new TreeNode(arr[i])
            queue.push(right)
            cur.right = right
        }
        i++
    }
    return root
}

var averageOfLevels = function (root) {
    const queue = [root]
    const arr = []
    while (queue.length > 0) {
        const len = queue.length
        let sum = 0
        for (let i = 0; i < len; i++) {
            const cur = queue.shift()
            if (cur.left) {
                queue.push(cur.left)
            }
            if (cur.right) {
                queue.push(cur.right)
            }
            sum += cur.val
        }
        arr.push(parseFloat((sum / len).toFixed(5)))
    }
    return arr
};
console.log(averageOfLevels(arrayToTree(root)));
